<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\facade\Db;

class DataContentGrabInit extends AdminBase
{
    public function index()
    {
        $param = $this->request->param();
        $db = Db::name('data_content_grab_init');
        if(!empty($param['kw'])){
            $db = $db->where('title','like','%'.$param['kw'].'%');
        }
        $list = $db->order('id desc')->field('id,title,dalei,xiaolei,project,source,channel,create_time')->paginate(['list_rows'=> 100,'query' => $param]);
        $count = $list->total();
        return view('index',['list'=>$list,'count'=>$count,'param'=>$param]);
    }

    public function add()
    {
        if( $this->request->isPost() ) {
            $param = $this->request->param();
            $result = Db::name('data_content_grab_init')->insert($param);
            if( $result ) {
                xn_add_admin_log('添加采集数据');
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }

        return view('form');
    }

    public function edit()
    {
        if( $this->request->isPost() ) {
            $param = $this->request->param();
            $result = Db::name('data_content_grab_init')->update($param);
            if( $result ) {
                xn_add_admin_log('修改采集数据');
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }
        $id = $this->request->get('id');
        $data = Db::name('data_content_grab_init')->find($id);

        return view('form',[
            'data'=>$data
        ]);
    }

    public function delete()
    {
        $id = intval($this->request->get('id'));
        !($id>0) && $this->error('参数错误');
        Db::name('data_content_grab_init')->delete($id);
        xn_add_admin_log('删除采集数据');
        $this->success('删除成功');
    }

    public function deleteAll(){
        $ids = $this->request->get('ids');
        ($ids=='') && $this->error('参数错误');
        $ids = explode(',',$ids);
        Db::name('data_content_grab_init')->delete($ids);
        xn_add_admin_log('批量删除采集数据');
        $this->success("删除成功");
    }

    public function clear(){
        Db::name('data_content_grab_init')->whereOr(['title'=>'','content'=>''])->delete();
        xn_add_admin_log('清除空的采集数据');
        $this->success("清除成功");
    }

    public function matching(){
        $matching = intval($this->request->get('matching'));
        $start = intval($this->request->get('start'));
        $end = intval($this->request->get('end'));
        if(empty($start) || empty($end)){
            $start = Db::name('data_content_grab_init')->where('matching',$matching)->field('id')->order('id asc')->find();
            $end = Db::name('data_content_grab_init')->where('matching',$matching)->field('id')->order('id desc')->find();
            if(!empty($start) && !empty($end)){
                $start = $start['id'];
                $end = $end['id'];
            }else{
                return json([
                    'status' => 0,
                    'msg' => '没有可匹配的数据'
                ]);
            }
        }
        if($start > $end){
            return json([
                'status' => 0,
                'msg' => '执行完毕'
            ]);
        }
        $map[] = ['matching','=',$matching];
        $limit = 1000;
        $nextStart = ($start+$limit);
        $map[] = ['id','>=',$start];
        $map[] = ['id','<',$nextStart];
        $list = Db::name('data_content_grab_init')->where($map)->field('id')->order('id asc')->select()->toArray();
        if(!empty($list)){
            foreach($list as $v){
                $r = $this->matchingOne($v['id']);
            }
        }
        $_nextStart = Db::name('data_content_grab_init')->where([
            ['matching','=',$matching],
            ['id','>=',$nextStart]
        ])->field('id')->order('id asc')->find();
        if(!empty($_nextStart)){
            $_start = $_nextStart['id'];
        }else{
            return json([
                'status' => 0,
                'msg' => '全部执行完毕'
            ]);
        }
        return json([
            'status' => 1,
            'msg' => '正在执行，ID:'.$start.'至'.$nextStart.'，结束ID:'.$end,
            'data' => ['start' => $_start, 'end' => $end]
        ]);
    }

    public function matchingOne($id){
        $id = intval($id);
        if($id <= 0){
            return json([
                'status' => 0,
                'msg' => '参数错误'
            ]);
        }
        $data = Db::name('data_content_grab_init')->field('id,title,content')->find($id)->toArray();
        //项目
        $matchData = Db::name('data_project')->field('id,typeid,title,alias')->select()->toArray();
        $r = $this->doMatchProject($data,$matchData);
        if($r){
            $data['project'] = $r['title'];
            $data['typeid'] = $r['typeid'];
            $data['parent_typeid'] = get_typepid($data['typeid'] );
            $data['top_typeid'] = get_typepid($data['parent_typeid']);
            $data['content'] = str_replace($data['project'],'{xiangmu}',$data['content']);
            $data['matching'] = 1;
        }else{
            //行业类型
            $matchData = Db::name('data_type')->field('id,alias')->where('level',2)->order('sort asc')->select()->toArray();
            $r = $this->doMatchOne($data,$matchData);
            if($r){
                $data['typeid'] = $r;
                $data['parent_typeid'] = get_typepid($data['typeid']);
                $data['top_typeid'] = get_typepid($data['parent_typeid']);
                $data['matching'] = 2;
            }else{
                $data['matching'] = -1;
                // $matchData = Db::name('data_type')->field('id,alias')->where('level',1)->select()->toArray();
                // $r = $this->doMatchOne($data,$matchData);
                // if($r){
                //     $data['parent_typeid'] = $r;
                //     $data['top_typeid'] = get_typepid($data['parent_typeid']);
                // }
            }
        }
        //属性
        $matchData = Db::name('data_tag_attr')->field('id,alias')->select()->toArray();
        $r = $this->doMatch($data,$matchData);
        if($r){
            $data['attr_ids'] = $r;
        }
        //人群
        $matchData = Db::name('data_tag_crowd')->field('id,alias')->select()->toArray();
        $r = $this->doMatch($data,$matchData);
        if($r){
            $data['crowd_ids'] = $r;
        }
        //投资金额
        $matchData = Db::name('data_tag_amount')->field('id,alias')->select()->toArray();
        $r = $this->doMatch($data,$matchData);
        if($r){
            $data['amount_ids'] = $r;
        }
        //选址
        $matchData = Db::name('data_tag_region')->field('id,alias')->select()->toArray();
        $r = $this->doMatch($data,$matchData);
        if($r){
            $data['region_ids'] = $r;
        }
        //经营
        $matchData = Db::name('data_tag_operate')->field('id,alias')->select()->toArray();
        $r = $this->doMatch($data,$matchData);
        if($r){
            $data['operate_ids'] = $r;
        }
        
        $result = Db::name('data_content_grab_init')->update($data);
        if( $result ) {
            return json([
                'status' => 1,
                'msg' => '操作成功'
            ]);
        } else {
            return json([
                'status' => 0,
                'msg' => '操作失败'
            ]);
        }
    }

    private function doMatch(&$data,&$matchData){
        $ids = '';
        foreach($matchData as $v){
            $alias_arr = explode(',',$v['alias']);
            foreach($alias_arr as $alias){
                if(strpos($data['title'],$alias) !== false){ 
                    $ids .= $v['id'].',';
                    break;
                }
            }
        }
        $ids = rtrim($ids,',');
        return $ids;
    }

    private function doMatchOne(&$data,&$matchData){
        foreach($matchData as $v){
            $alias_arr = explode(',',$v['alias']);
            foreach($alias_arr as $alias){
                if(strpos($data['title'],$alias) !== false){ 
                    return $v['id'];
                }
            }
        }
    }

    private function doMatchProject(&$data,&$matchData){
        foreach($matchData as $v){
            $alias_arr = explode(',',$v['alias']);
            foreach($alias_arr as $alias){
                if(strpos($data['title'],$alias) !== false){ 
                    return $v;
                }
            }
        }
    }


}
